home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / perlcl16.lha / perlclass1.6 / regex.c < prev    next >
C/C++ Source or Header  |  1992-10-18  |  28KB  |  1,220 lines

  1. /*
  2.  * regcomp and regexec -- regsub and regerror are elsewhere
  3.  *
  4.  *    Copyright (c) 1986 by University of Toronto.
  5.  *    Written by Henry Spencer.  Not derived from licensed software.
  6.  *
  7.  *    Permission is granted to anyone to use this software for any
  8.  *    purpose on any computer system, and to redistribute it freely,
  9.  *    subject to the following restrictions:
  10.  *
  11.  *    1. The author is not responsible for the consequences of use of
  12.  *        this software, no matter how awful, even if they arise
  13.  *        from defects in it.
  14.  *
  15.  *    2. The origin of this software must not be misrepresented, either
  16.  *        by explicit claim or by omission.
  17.  *
  18.  *    3. Altered versions must be plainly marked as such, and must not
  19.  *        be misrepresented as being the original software.
  20.  *
  21.  * Beware that some of this code is subtly aware of the way operator
  22.  * precedence is structured in regular expressions.  Serious changes in
  23.  * regular-expression syntax might require a total rethink.
  24.  */
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include "regex.h"
  28. #include "regmagic.h"
  29.  
  30. /*
  31.  * The "internal use only" fields in regexp.h are present to pass info from
  32.  * compile to execute that permits the execute phase to run lots faster on
  33.  * simple cases.  They are:
  34.  *
  35.  * regstart    char that must begin a match; '\0' if none obvious
  36.  * reganch    is the match anchored (at beginning-of-line only)?
  37.  * regmust    string (pointer into program) that match must include, or NULL
  38.  * regmlen    length of regmust string
  39.  *
  40.  * Regstart and reganch permit very fast decisions on suitable starting points
  41.  * for a match, cutting down the work a lot.  Regmust permits fast rejection
  42.  * of lines that cannot possibly match.  The regmust tests are costly enough
  43.  * that regcomp() supplies a regmust only if the r.e. contains something
  44.  * potentially expensive (at present, the only such thing detected is * or +
  45.  * at the start of the r.e., which can involve a lot of backup).  Regmlen is
  46.  * supplied because the test in regexec() needs it and regcomp() is computing
  47.  * it anyway.
  48.  */
  49.  
  50. /*
  51.  * Structure for regexp "program".  This is essentially a linear encoding
  52.  * of a nondeterministic finite-state machine (aka syntax charts or
  53.  * "railroad normal form" in parsing technology).  Each node is an opcode
  54.  * plus a "next" pointer, possibly plus an operand.  "Next" pointers of
  55.  * all nodes except BRANCH implement concatenation; a "next" pointer with
  56.  * a BRANCH on both ends of it is connecting two alternatives.  (Here we
  57.  * have one of the subtle syntax dependencies:  an individual BRANCH (as
  58.  * opposed to a collection of them) is never concatenated with anything
  59.  * because of operator precedence.)  The operand of some types of node is
  60.  * a literal string; for others, it is a node leading into a sub-FSM.  In
  61.  * particular, the operand of a BRANCH node is the first node of the branch.
  62.  * (NB this is *not* a tree structure:  the tail of the branch connects
  63.  * to the thing following the set of BRANCHes.)  The opcodes are:
  64.  */
  65.  
  66. /* definition    number    opnd?    meaning */
  67. #define    END    0    /* no    End of program. */
  68. #define    BOL    1    /* no    Match "" at beginning of line. */
  69. #define    EOL    2    /* no    Match "" at end of line. */
  70. #define    ANY    3    /* no    Match any one character. */
  71. #define    ANYOF    4    /* str    Match any character in this string. */
  72. #define    ANYBUT    5    /* str    Match any character not in this string. */
  73. #define    BRANCH    6    /* node    Match this alternative, or the next... */
  74. #define    BACK    7    /* no    Match "", "next" ptr points backward. */
  75. #define    EXACTLY    8    /* str    Match this string. */
  76. #define    NOTHING    9    /* no    Match empty string. */
  77. #define    STAR    10    /* node    Match this (simple) thing 0 or more times. */
  78. #define    PLUS    11    /* node    Match this (simple) thing 1 or more times. */
  79. #define    OPEN    20    /* no    Mark this point in input as start of #n. */
  80.             /*    OPEN+1 is number 1, etc. */
  81. #define    CLOSE    30    /* no    Analogous to OPEN. */
  82.  
  83. /*
  84.  * Opcode notes:
  85.  *
  86.  * BRANCH    The set of branches constituting a single choice are hooked
  87.  *        together with their "next" pointers, since precedence prevents
  88.  *        anything being concatenated to any individual branch.  The
  89.  *        "next" pointer of the last BRANCH in a choice points to the
  90.  *        thing following the whole choice.  This is also where the
  91.  *        final "next" pointer of each individual branch points; each
  92.  *        branch starts with the operand node of a BRANCH node.
  93.  *
  94.  * BACK        Normal "next" pointers all implicitly point forward; BACK
  95.  *        exists to make loop structures possible.
  96.  *
  97.  * STAR,PLUS    '?', and complex '*' and '+', are implemented as circular
  98.  *        BRANCH structures using BACK.  Simple cases (one character
  99.  *        per match) are implemented with STAR and PLUS for speed
  100.  *        and to minimize recursive plunges.
  101.  *
  102.  * OPEN,CLOSE    ...are numbered at compile time.
  103.  */
  104.  
  105. /*
  106.  * A node is one char of opcode followed by two chars of "next" pointer.
  107.  * "Next" pointers are stored as two 8-bit pieces, high order first.  The
  108.  * value is a positive offset from the opcode of the node containing it.
  109.  * An operand, if any, simply follows the node.  (Note that much of the
  110.  * code generation knows about this implicit relationship.)
  111.  *
  112.  * Using two bytes for the "next" pointer is vast overkill for most things,
  113.  * but allows patterns to get big without disasters.
  114.  */
  115. #define    OP(p)    (*(p))
  116. #define    NEXT(p)    (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
  117. #define    OPERAND(p)    ((p) + 3)
  118.  
  119. /*
  120.  * See regmagic.h for one further detail of program structure.
  121.  */
  122.  
  123.  
  124. /*
  125.  * Utility definitions.
  126.  */
  127. #ifndef CHARBITS
  128. #define    UCHARAT(p)    ((int)*(unsigned char *)(p))
  129. #else
  130. #define    UCHARAT(p)    ((int)*(p)&CHARBITS)
  131. #endif
  132.  
  133. #define    FAIL(m)    { regerror(m); return(NULL); }
  134. #define    ISMULT(c)    ((c) == '*' || (c) == '+' || (c) == '?')
  135. #define    META    "^$.[()|?+*\\"
  136.  
  137. /*
  138.  * Flags to be passed up and down.
  139.  */
  140. #define    HASWIDTH    01    /* Known never to match null string. */
  141. #define    SIMPLE        02    /* Simple enough to be STAR/PLUS operand. */
  142. #define    SPSTART        04    /* Starts with * or +. */
  143. #define    WORST        0    /* Worst case. */
  144.  
  145. /*
  146.  * Global work variables for regcomp().
  147.  */
  148. static char *regparse;        /* Input-scan pointer. */
  149. static int regnpar;        /* () count. */
  150. static char regdummy;
  151. static char *regcode;        /* Code-emit pointer; ®dummy = don't. */
  152. static long regsize;        /* Code size. */
  153.  
  154. /*
  155.  * Forward declarations for regcomp()'s friends.
  156.  */
  157. #ifndef STATIC
  158. #define    STATIC    static
  159. #endif
  160. STATIC char *reg();
  161. STATIC char *regbranch();
  162. STATIC char *regpiece();
  163. STATIC char *regatom();
  164. STATIC char *regnode();
  165. STATIC char *regnext();
  166. STATIC void regc();
  167. STATIC void reginsert();
  168. STATIC void regtail();
  169. STATIC void regoptail();
  170. #ifdef STRCSPN
  171. STATIC int strcspn();
  172. #endif
  173.  
  174. /*
  175.  - regcomp - compile a regular expression into internal code
  176.  *
  177.  * We can't allocate space until we know how big the compiled form will be,
  178.  * but we can't compile it (and thus know how big it is) until we've got a
  179.  * place to put the code.  So we cheat:  we compile it twice, once with code
  180.  * generation turned off and size counting turned on, and once "for real".
  181.  * This also means that we don't allocate space until we are sure that the
  182.  * thing really will compile successfully, and we never have to move the
  183.  * code and thus invalidate pointers into it.  (Note that it has to be in
  184.  * one piece because free() must be able to free it all.)
  185.  *
  186.  * Beware that the optimization-preparation code in here knows about some
  187.  * of the structure of the compiled regexp.
  188.  */
  189. regexp *
  190. regcomp(exp)
  191. char *exp;
  192. {
  193.     register regexp *r;
  194.     register char *scan;
  195.     register char *longest;
  196.     register int len;
  197.     int flags;
  198.  
  199.     if (exp == NULL)
  200.         FAIL("NULL argument");
  201.  
  202.     /* First pass: determine size, legality. */
  203.     regparse = exp;
  204.     regnpar = 1;
  205.     regsize = 0L;
  206.     regcode = ®dummy;
  207.     regc(MAGIC);
  208.     if (reg(0, &flags) == NULL)
  209.         return(NULL);
  210.  
  211.     /* Small enough for pointer-storage convention? */
  212.     if (regsize >= 32767L)        /* Probably could be 65535L. */
  213.         FAIL("regexp too big");
  214.  
  215.     /* Allocate space. */
  216.     r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize);
  217.     if (r == NULL)
  218.         FAIL("out of space");
  219.  
  220.     /* Second pass: emit code. */
  221.     regparse = exp;
  222.     regnpar = 1;
  223.     regcode = r->program;
  224.     regc(MAGIC);
  225.     if (reg(0, &flags) == NULL)
  226.         return(NULL);
  227.  
  228.     /* Dig out information for optimizations. */
  229.     r->regstart = '\0';    /* Worst-case defaults. */
  230.     r->reganch = 0;
  231.     r->regmust = NULL;
  232.     r->regmlen = 0;
  233.     scan = r->program+1;            /* First BRANCH. */
  234.     if (OP(regnext(scan)) == END) {        /* Only one top-level choice. */
  235.         scan = OPERAND(scan);
  236.  
  237.         /* Starting-point info. */
  238.         if (OP(scan) == EXACTLY)
  239.             r->regstart = *OPERAND(scan);
  240.         else if (OP(scan) == BOL)
  241.             r->reganch++;
  242.  
  243.         /*
  244.          * If there's something expensive in the r.e., find the
  245.          * longest literal string that must appear and make it the
  246.          * regmust.  Resolve ties in favor of later strings, since
  247.          * the regstart check works with the beginning of the r.e.
  248.          * and avoiding duplication strengthens checking.  Not a
  249.          * strong reason, but sufficient in the absence of others.
  250.          */
  251.         if (flags&SPSTART) {
  252.             longest = NULL;
  253.             len = 0;
  254.             for (; scan != NULL; scan = regnext(scan))
  255.                 if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
  256.                     longest = OPERAND(scan);
  257.                     len = strlen(OPERAND(scan));
  258.                 }
  259.             r->regmust = longest;
  260.             r->regmlen = len;
  261.         }
  262.     }
  263.  
  264.     return(r);
  265. }
  266.  
  267. /*
  268.  - reg - regular expression, i.e. main body or parenthesized thing
  269.  *
  270.  * Caller must absorb opening parenthesis.
  271.  *
  272.  * Combining parenthesis handling with the base level of regular expression
  273.  * is a trifle forced, but the need to tie the tails of the branches to what
  274.  * follows makes it hard to avoid.
  275.  */
  276. static char *
  277. reg(paren, flagp)
  278. int paren;            /* Parenthesized? */
  279. int *flagp;
  280. {
  281.     register char *ret;
  282.     register char *br;
  283.     register char *ender;
  284.     register int parno;
  285.     int flags;
  286.  
  287.     *flagp = HASWIDTH;    /* Tentatively. */
  288.  
  289.     /* Make an OPEN node, if parenthesized. */
  290.     if (paren) {
  291.         if (regnpar >= NSUBEXP)
  292.             FAIL("too many ()");
  293.         parno = regnpar;
  294.         regnpar++;
  295.         ret = regnode(OPEN+parno);
  296.     } else
  297.         ret = NULL;
  298.  
  299.     /* Pick up the branches, linking them together. */
  300.     br = regbranch(&flags);
  301.     if (br == NULL)
  302.         return(NULL);
  303.     if (ret != NULL)
  304.         regtail(ret, br);    /* OPEN -> first. */
  305.     else
  306.         ret = br;
  307.     if (!(flags&HASWIDTH))
  308.         *flagp &= ~HASWIDTH;
  309.     *flagp |= flags&SPSTART;
  310.     while (*regparse == '|') {
  311.         regparse++;
  312.         br = regbranch(&flags);
  313.         if (br == NULL)
  314.             return(NULL);
  315.         regtail(ret, br);    /* BRANCH -> BRANCH. */
  316.         if (!(flags&HASWIDTH))
  317.             *flagp &= ~HASWIDTH;
  318.         *flagp |= flags&SPSTART;
  319.     }
  320.  
  321.     /* Make a closing node, and hook it on the end. */
  322.     ender = regnode((paren) ? CLOSE+parno : END);    
  323.     regtail(ret, ender);
  324.  
  325.     /* Hook the tails of the branches to the closing node. */
  326.     for (br = ret; br != NULL; br = regnext(br))
  327.         regoptail(br, ender);
  328.  
  329.     /* Check for proper termination. */
  330.     if (paren && *regparse++ != ')') {
  331.         FAIL("unmatched ()");
  332.     } else if (!paren && *regparse != '\0') {
  333.         if (*regparse == ')') {
  334.             FAIL("unmatched ()");
  335.         } else
  336.             FAIL("junk on end");    /* "Can't happen". */
  337.         /* NOTREACHED */
  338.     }
  339.  
  340.     return(ret);
  341. }
  342.  
  343. /*
  344.  - regbranch - one alternative of an | operator
  345.  *
  346.  * Implements the concatenation operator.
  347.  */
  348. static char *
  349. regbranch(flagp)
  350. int *flagp;
  351. {
  352.     register char *ret;
  353.     register char *chain;
  354.     register char *latest;
  355.     int flags;
  356.  
  357.     *flagp = WORST;        /* Tentatively. */
  358.  
  359.     ret = regnode(BRANCH);
  360.     chain = NULL;
  361.     while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
  362.         latest = regpiece(&flags);
  363.         if (latest == NULL)
  364.             return(NULL);
  365.         *flagp |= flags&HASWIDTH;
  366.         if (chain == NULL)    /* First piece. */
  367.             *flagp |= flags&SPSTART;
  368.         else
  369.             regtail(chain, latest);
  370.         chain = latest;
  371.     }
  372.     if (chain == NULL)    /* Loop ran zero times. */
  373.         (void) regnode(NOTHING);
  374.  
  375.     return(ret);
  376. }
  377.  
  378. /*
  379.  - regpiece - something followed by possible [*+?]
  380.  *
  381.  * Note that the branching code sequences used for ? and the general cases
  382.  * of * and + are somewhat optimized:  they use the same NOTHING node as
  383.  * both the endmarker for their branch list and the body of the last branch.
  384.  * It might seem that this node could be dispensed with entirely, but the
  385.  * endmarker role is not redundant.
  386.  */
  387. static char *
  388. regpiece(flagp)
  389. int *flagp;
  390. {
  391.     register char *ret;
  392.     register char op;
  393.     register char *next;
  394.     int flags;
  395.  
  396.     ret = regatom(&flags);
  397.     if (ret == NULL)
  398.         return(NULL);
  399.  
  400.     op = *regparse;
  401.     if (!ISMULT(op)) {
  402.         *flagp = flags;
  403.         return(ret);
  404.     }
  405.  
  406.     if (!(flags&HASWIDTH) && op != '?')
  407.         FAIL("*+ operand could be empty");
  408.     *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
  409.  
  410.     if (op == '*' && (flags&SIMPLE))
  411.         reginsert(STAR, ret);
  412.     else if (op == '*') {
  413.         /* Emit x* as (x&|), where & means "self". */
  414.         reginsert(BRANCH, ret);            /* Either x */
  415.         regoptail(ret, regnode(BACK));        /* and loop */
  416.         regoptail(ret, ret);            /* back */
  417.         regtail(ret, regnode(BRANCH));        /* or */
  418.         regtail(ret, regnode(NOTHING));        /* null. */
  419.     } else if (op == '+' && (flags&SIMPLE))
  420.         reginsert(PLUS, ret);
  421.     else if (op == '+') {
  422.         /* Emit x+ as x(&|), where & means "self". */
  423.         next = regnode(BRANCH);            /* Either */
  424.         regtail(ret, next);
  425.         regtail(regnode(BACK), ret);        /* loop back */
  426.         regtail(next, regnode(BRANCH));        /* or */
  427.         regtail(ret, regnode(NOTHING));        /* null. */
  428.     } else if (op == '?') {
  429.         /* Emit x? as (x|) */
  430.         reginsert(BRANCH, ret);            /* Either x */
  431.         regtail(ret, regnode(BRANCH));        /* or */
  432.         next = regnode(NOTHING);        /* null. */
  433.         regtail(ret, next);
  434.         regoptail(ret, next);
  435.     }
  436.     regparse++;
  437.     if (ISMULT(*regparse))
  438.         FAIL("nested *?+");
  439.  
  440.     return(ret);
  441. }
  442.  
  443. /*
  444.  - regatom - the lowest level
  445.  *
  446.  * Optimization:  gobbles an entire sequence of ordinary characters so that
  447.  * it can turn them into a single node, which is smaller to store and
  448.  * faster to run.  Backslashed characters are exceptions, each becoming a
  449.  * separate node; the code is simpler that way and it's not worth fixing.
  450.  */
  451. static char *
  452. regatom(flagp)
  453. int *flagp;
  454. {
  455.     register char *ret;
  456.     int flags;
  457.  
  458.     *flagp = WORST;        /* Tentatively. */
  459.  
  460.     switch (*regparse++) {
  461.     case '^':
  462.         ret = regnode(BOL);
  463.         break;
  464.     case '$':
  465.         ret = regnode(EOL);
  466.         break;
  467.     case '.':
  468.         ret = regnode(ANY);
  469.         *flagp |= HASWIDTH|SIMPLE;
  470.         break;
  471.     case '[': {
  472.             register int class;
  473.             register int classend;
  474.  
  475.             if (*regparse == '^') {    /* Complement of range. */
  476.                 ret = regnode(ANYBUT);
  477.                 regparse++;
  478.             } else
  479.                 ret = regnode(ANYOF);
  480.             if (*regparse == ']' || *regparse == '-')
  481.                 regc(*regparse++);
  482.             while (*regparse != '\0' && *regparse != ']') {
  483.                 if (*regparse == '-') {
  484.                     regparse++;
  485.                     if (*regparse == ']' || *regparse == '\0')
  486.                         regc('-');
  487.                     else {
  488.                         class = UCHARAT(regparse-2)+1;
  489.                         classend = UCHARAT(regparse);
  490.                         if (class > classend+1)
  491.                             FAIL("invalid [] range");
  492.                         for (; class <= classend; class++)
  493.                             regc(class);
  494.                         regparse++;
  495.                     }
  496.                 } else
  497.                     regc(*regparse++);
  498.             }
  499.             regc('\0');
  500.             if (*regparse != ']')
  501.                 FAIL("unmatched []");
  502.             regparse++;
  503.             *flagp |= HASWIDTH|SIMPLE;
  504.         }
  505.         break;
  506.     case '(':
  507.         ret = reg(1, &flags);
  508.         if (ret == NULL)
  509.             return(NULL);
  510.         *flagp |= flags&(HASWIDTH|SPSTART);
  511.         break;
  512.     case '\0':
  513.     case '|':
  514.     case ')':
  515.         FAIL("internal urp");    /* Supposed to be caught earlier. */
  516.         break;
  517.     case '?':
  518.     case '+':
  519.     case '*':
  520.         FAIL("?+* follows nothing");
  521.         break;
  522.     case '\\':
  523.         if (*regparse == '\0')
  524.             FAIL("trailing \\");
  525.         ret = regnode(EXACTLY);
  526.         regc(*regparse++);
  527.         regc('\0');
  528.         *flagp |= HASWIDTH|SIMPLE;
  529.         break;
  530.     default: {
  531.             register int len;
  532.             register char ender;
  533.  
  534.             regparse--;
  535.             len = strcspn(regparse, META);
  536.             if (len <= 0)
  537.                 FAIL("internal disaster");
  538.             ender = *(regparse+len);
  539.             if (len > 1 && ISMULT(ender))
  540.                 len--;        /* Back off clear of ?+* operand. */
  541.             *flagp |= HASWIDTH;
  542.             if (len == 1)
  543.                 *flagp |= SIMPLE;
  544.             ret = regnode(EXACTLY);
  545.             while (len > 0) {
  546.                 regc(*regparse++);
  547.                 len--;
  548.             }
  549.             regc('\0');
  550.         }
  551.         break;
  552.     }
  553.  
  554.     return(ret);
  555. }
  556.  
  557. /*
  558.  - regnode - emit a node
  559.  */
  560. static char *            /* Location. */
  561. regnode(op)
  562. char op;
  563. {
  564.     register char *ret;
  565.     register char *ptr;
  566.  
  567.     ret = regcode;
  568.     if (ret == ®dummy) {
  569.         regsize += 3;
  570.         return(ret);
  571.     }
  572.  
  573.     ptr = ret;
  574.     *ptr++ = op;
  575.     *ptr++ = '\0';        /* Null "next" pointer. */
  576.     *ptr++ = '\0';
  577.     regcode = ptr;
  578.  
  579.     return(ret);
  580. }
  581.  
  582. /*
  583.  - regc - emit (if appropriate) a byte of code
  584.  */
  585. static void
  586. regc(b)
  587. char b;
  588. {
  589.     if (regcode != ®dummy)
  590.         *regcode++ = b;
  591.     else
  592.         regsize++;
  593. }
  594.  
  595. /*
  596.  - reginsert - insert an operator in front of already-emitted operand
  597.  *
  598.  * Means relocating the operand.
  599.  */
  600. static void
  601. reginsert(op, opnd)
  602. char op;
  603. char *opnd;
  604. {
  605.     register char *src;
  606.     register char *dst;
  607.     register char *place;
  608.  
  609.     if (regcode == ®dummy) {
  610.         regsize += 3;
  611.         return;
  612.     }
  613.  
  614.     src = regcode;
  615.     regcode += 3;
  616.     dst = regcode;
  617.     while (src > opnd)
  618.         *--dst = *--src;
  619.  
  620.     place = opnd;        /* Op node, where operand used to be. */
  621.     *place++ = op;
  622.     *place++ = '\0';
  623.     *place++ = '\0';
  624. }
  625.  
  626. /*
  627.  - regtail - set the next-pointer at the end of a node chain
  628.  */
  629. static void
  630. regtail(p, val)
  631. char *p;
  632. char *val;
  633. {
  634.     register char *scan;
  635.     register char *temp;
  636.     register int offset;
  637.  
  638.     if (p == ®dummy)
  639.         return;
  640.  
  641.     /* Find last node. */
  642.     scan = p;
  643.     for (;;) {
  644.         temp = regnext(scan);
  645.         if (temp == NULL)
  646.             break;
  647.         scan = temp;
  648.     }
  649.  
  650.     if (OP(scan) == BACK)
  651.         offset = scan - val;
  652.     else
  653.         offset = val - scan;
  654.     *(scan+1) = (offset>>8)&0377;
  655.     *(scan+2) = offset&0377;
  656. }
  657.  
  658. /*
  659.  - regoptail - regtail on operand of first argument; nop if operandless
  660.  */
  661. static void
  662. regoptail(p, val)
  663. char *p;
  664. char *val;
  665. {
  666.     /* "Operandless" and "op != BRANCH" are synonymous in practice. */
  667.     if (p == NULL || p == ®dummy || OP(p) != BRANCH)
  668.         return;
  669.     regtail(OPERAND(p), val);
  670. }
  671.  
  672. /*
  673.  * regexec and friends
  674.  */
  675.  
  676. /*
  677.  * Global work variables for regexec().
  678.  */
  679. static char *reginput;        /* String-input pointer. */
  680. static char *regbol;        /* Beginning of input, for ^ check. */
  681. static char **regstartp;    /* Pointer to startp array. */
  682. static char **regendp;        /* Ditto for endp. */
  683.  
  684. /*
  685.  * Forwards.
  686.  */
  687. STATIC int regtry();
  688. STATIC int regmatch();
  689. STATIC int regrepeat();
  690.  
  691. #ifdef DEBUG
  692. int regnarrate = 0;
  693. void regdump();
  694. STATIC char *regprop();
  695. #endif
  696.  
  697. /*
  698.  - regexec - match a regexp against a string
  699.  */
  700. int
  701. regexec(prog, string)
  702. register regexp *prog;
  703. register char *string;
  704. {
  705.     register char *s;
  706.     extern char *strchr();
  707.  
  708.     /* Be paranoid... */
  709.     if (prog == NULL || string == NULL) {
  710.         regerror("NULL parameter");
  711.         return(0);
  712.     }
  713.  
  714.     /* Check validity of program. */
  715.     if (UCHARAT(prog->program) != MAGIC) {
  716.         regerror("corrupted program");
  717.         return(0);
  718.     }
  719.  
  720.     /* If there is a "must appear" string, look for it. */
  721.     if (prog->regmust != NULL) {
  722.         s = string;
  723.         while ((s = strchr(s, prog->regmust[0])) != NULL) {
  724.             if (strncmp(s, prog->regmust, prog->regmlen) == 0)
  725.                 break;    /* Found it. */
  726.             s++;
  727.         }
  728.         if (s == NULL)    /* Not present. */
  729.             return(0);
  730.     }
  731.  
  732.     /* Mark beginning of line for ^ . */
  733.     regbol = string;
  734.  
  735.     /* Simplest case:  anchored match need be tried only once. */
  736.     if (prog->reganch)
  737.         return(regtry(prog, string));
  738.  
  739.     /* Messy cases:  unanchored match. */
  740.     s = string;
  741.     if (prog->regstart != '\0')
  742.         /* We know what char it must start with. */
  743.         while ((s = strchr(s, prog->regstart)) != NULL) {
  744.             if (regtry(prog, s))
  745.                 return(1);
  746.             s++;
  747.         }
  748.     else
  749.         /* We don't -- general case. */
  750.         do {
  751.             if (regtry(prog, s))
  752.                 return(1);
  753.         } while (*s++ != '\0');
  754.  
  755.     /* Failure. */
  756.     return(0);
  757. }
  758.  
  759. /*
  760.  - regtry - try match at specific point
  761.  */
  762. static int            /* 0 failure, 1 success */
  763. regtry(prog, string)
  764. regexp *prog;
  765. char *string;
  766. {
  767.     register int i;
  768.     register char **sp;
  769.     register char **ep;
  770.  
  771.     reginput = string;
  772.     regstartp = prog->startp;
  773.     regendp = prog->endp;
  774.  
  775.     sp = prog->startp;
  776.     ep = prog->endp;
  777.     for (i = NSUBEXP; i > 0; i--) {
  778.         *sp++ = NULL;
  779.         *ep++ = NULL;
  780.     }
  781.     if (regmatch(prog->program + 1)) {
  782.         prog->startp[0] = string;
  783.         prog->endp[0] = reginput;
  784.         return(1);
  785.     } else
  786.         return(0);
  787. }
  788.  
  789. /*
  790.  - regmatch - main matching routine
  791.  *
  792.  * Conceptually the strategy is simple:  check to see whether the current
  793.  * node matches, call self recursively to see whether the rest matches,
  794.  * and then act accordingly.  In practice we make some effort to avoid
  795.  * recursion, in particular by going through "ordinary" nodes (that don't
  796.  * need to know whether the rest of the match failed) by a loop instead of
  797.  * by recursion.
  798.  */
  799. static int            /* 0 failure, 1 success */
  800. regmatch(prog)
  801. char *prog;
  802. {
  803.     register char *scan;    /* Current node. */
  804.     char *next;        /* Next node. */
  805.     extern char *strchr();
  806.  
  807.     scan = prog;
  808. #ifdef DEBUG
  809.     if (scan != NULL && regnarrate)
  810.         fprintf(stderr, "%s(\n", regprop(scan));
  811. #endif
  812.     while (scan != NULL) {
  813. #ifdef DEBUG
  814.         if (regnarrate)
  815.             fprintf(stderr, "%s...\n", regprop(scan));
  816. #endif
  817.         next = regnext(scan);
  818.  
  819.         switch (OP(scan)) {
  820.         case BOL:
  821.             if (reginput != regbol)
  822.                 return(0);
  823.             break;
  824.         case EOL:
  825.             if (*reginput != '\0')
  826.                 return(0);
  827.             break;
  828.         case ANY:
  829.             if (*reginput == '\0')
  830.                 return(0);
  831.             reginput++;
  832.             break;
  833.         case EXACTLY: {
  834.                 register int len;
  835.                 register char *opnd;
  836.  
  837.                 opnd = OPERAND(scan);
  838.                 /* Inline the first character, for speed. */
  839.                 if (*opnd != *reginput)
  840.                     return(0);
  841.                 len = strlen(opnd);
  842.                 if (len > 1 && strncmp(opnd, reginput, len) != 0)
  843.                     return(0);
  844.                 reginput += len;
  845.             }
  846.             break;
  847.         case ANYOF:
  848.              if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == NULL)
  849.                 return(0);
  850.             reginput++;
  851.             break;
  852.         case ANYBUT:
  853.              if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != NULL)
  854.                 return(0);
  855.             reginput++;
  856.             break;
  857.         case NOTHING:
  858.             break;
  859.         case BACK:
  860.             break;
  861.         case OPEN+1:
  862.         case OPEN+2:
  863.         case OPEN+3:
  864.         case OPEN+4:
  865.         case OPEN+5:
  866.         case OPEN+6:
  867.         case OPEN+7:
  868.         case OPEN+8:
  869.         case OPEN+9: {
  870.                 register int no;
  871.                 register char *save;
  872.  
  873.                 no = OP(scan) - OPEN;
  874.                 save = reginput;
  875.  
  876.                 if (regmatch(next)) {
  877.                     /*
  878.                      * Don't set startp if some later
  879.                      * invocation of the same parentheses
  880.                      * already has.
  881.                      */
  882.                     if (regstartp[no] == NULL)
  883.                         regstartp[no] = save;
  884.                     return(1);
  885.                 } else
  886.                     return(0);
  887.             }
  888.             break;
  889.         case CLOSE+1:
  890.         case CLOSE+2:
  891.         case CLOSE+3:
  892.         case CLOSE+4:
  893.         case CLOSE+5:
  894.         case CLOSE+6:
  895.         case CLOSE+7:
  896.         case CLOSE+8:
  897.         case CLOSE+9: {
  898.                 register int no;
  899.                 register char *save;
  900.  
  901.                 no = OP(scan) - CLOSE;
  902.                 save = reginput;
  903.  
  904.                 if (regmatch(next)) {
  905.                     /*
  906.                      * Don't set endp if some later
  907.                      * invocation of the same parentheses
  908.                      * already has.
  909.                      */
  910.                     if (regendp[no] == NULL)
  911.                         regendp[no] = save;
  912.                     return(1);
  913.                 } else
  914.                     return(0);
  915.             }
  916.             break;
  917.         case BRANCH: {
  918.                 register char *save;
  919.  
  920.                 if (OP(next) != BRANCH)        /* No choice. */
  921.                     next = OPERAND(scan);    /* Avoid recursion. */
  922.                 else {
  923.                     do {
  924.                         save = reginput;
  925.                         if (regmatch(OPERAND(scan)))
  926.                             return(1);
  927.                         reginput = save;
  928.                         scan = regnext(scan);
  929.                     } while (scan != NULL && OP(scan) == BRANCH);
  930.                     return(0);
  931.                     /* NOTREACHED */
  932.                 }
  933.             }
  934.             break;
  935.         case STAR:
  936.         case PLUS: {
  937.                 register char nextch;
  938.                 register int no;
  939.                 register char *save;
  940.                 register int min;
  941.  
  942.                 /*
  943.                  * Lookahead to avoid useless match attempts
  944.                  * when we know what character comes next.
  945.                  */
  946.                 nextch = '\0';
  947.                 if (OP(next) == EXACTLY)
  948.                     nextch = *OPERAND(next);
  949.                 min = (OP(scan) == STAR) ? 0 : 1;
  950.                 save = reginput;
  951.                 no = regrepeat(OPERAND(scan));
  952.                 while (no >= min) {
  953.                     /* If it could work, try it. */
  954.                     if (nextch == '\0' || *reginput == nextch)
  955.                         if (regmatch(next))
  956.                             return(1);
  957.                     /* Couldn't or didn't -- back up. */
  958.                     no--;
  959.                     reginput = save + no;
  960.                 }
  961.                 return(0);
  962.             }
  963.             break;
  964.         case END:
  965.             return(1);    /* Success! */
  966.             break;
  967.         default:
  968.             regerror("memory corruption");
  969.             return(0);
  970.             break;
  971.         }
  972.  
  973.         scan = next;
  974.     }
  975.  
  976.     /*
  977.      * We get here only if there's trouble -- normally "case END" is
  978.      * the terminating point.
  979.      */
  980.     regerror("corrupted pointers");
  981.     return(0);
  982. }
  983.  
  984. /*
  985.  - regrepeat - repeatedly match something simple, report how many
  986.  */
  987. static int
  988. regrepeat(p)
  989. char *p;
  990. {
  991.       char *strchr();
  992.     register int count = 0;
  993.     register char *scan;
  994.     register char *opnd;
  995.  
  996.     scan = reginput;
  997.     opnd = OPERAND(p);
  998.     switch (OP(p)) {
  999.     case ANY:
  1000.         count = strlen(scan);
  1001.         scan += count;
  1002.         break;
  1003.     case EXACTLY:
  1004.         while (*opnd == *scan) {
  1005.             count++;
  1006.             scan++;
  1007.         }
  1008.         break;
  1009.     case ANYOF:
  1010.         while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
  1011.             count++;
  1012.             scan++;
  1013.         }
  1014.         break;
  1015.     case ANYBUT:
  1016.         while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
  1017.             count++;
  1018.             scan++;
  1019.         }
  1020.         break;
  1021.     default:        /* Oh dear.  Called inappropriately. */
  1022.         regerror("internal foulup");
  1023.         count = 0;    /* Best compromise. */
  1024.         break;
  1025.     }
  1026.     reginput = scan;
  1027.  
  1028.     return(count);
  1029. }
  1030.  
  1031. /*
  1032.  - regnext - dig the "next" pointer out of a node
  1033.  */
  1034. static char *
  1035. regnext(p)
  1036. register char *p;
  1037. {
  1038.     register int offset;
  1039.  
  1040.     if (p == ®dummy)
  1041.         return(NULL);
  1042.  
  1043.     offset = NEXT(p);
  1044.     if (offset == 0)
  1045.         return(NULL);
  1046.  
  1047.     if (OP(p) == BACK)
  1048.         return(p-offset);
  1049.     else
  1050.         return(p+offset);
  1051. }
  1052.  
  1053. #ifdef DEBUG
  1054.  
  1055. STATIC char *regprop();
  1056.  
  1057. /*
  1058.  - regdump - dump a regexp onto stdout in vaguely comprehensible form
  1059.  */
  1060. void
  1061. regdump(r)
  1062. regexp *r;
  1063. {
  1064.     register char *s;
  1065.     register char op = EXACTLY;    /* Arbitrary non-END op. */
  1066.     register char *next;
  1067.     extern char *strchr();
  1068.  
  1069.  
  1070.     s = r->program + 1;
  1071.     while (op != END) {    /* While that wasn't END last time... */
  1072.         op = OP(s);
  1073.         printf("%2d%s", s-r->program, regprop(s));    /* Where, what. */
  1074.         next = regnext(s);
  1075.         if (next == NULL)        /* Next ptr. */
  1076.             printf("(0)");
  1077.         else 
  1078.             printf("(%d)", (s-r->program)+(next-s));
  1079.         s += 3;
  1080.         if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
  1081.             /* Literal string, where present. */
  1082.             while (*s != '\0') {
  1083.                 putchar(*s);
  1084.                 s++;
  1085.             }
  1086.             s++;
  1087.         }
  1088.         putchar('\n');
  1089.     }
  1090.  
  1091.     /* Header fields of interest. */
  1092.     if (r->regstart != '\0')
  1093.         printf("start `%c' ", r->regstart);
  1094.     if (r->reganch)
  1095.         printf("anchored ");
  1096.     if (r->regmust != NULL)
  1097.         printf("must have \"%s\"", r->regmust);
  1098.     printf("\n");
  1099. }
  1100.  
  1101. /*
  1102.  - regprop - printable representation of opcode
  1103.  */
  1104. static char *
  1105. regprop(op)
  1106. char *op;
  1107. {
  1108.     register char *p;
  1109.     static char buf[50];
  1110.  
  1111.     (void) strcpy(buf, ":");
  1112.  
  1113.     switch (OP(op)) {
  1114.     case BOL:
  1115.         p = "BOL";
  1116.         break;
  1117.     case EOL:
  1118.         p = "EOL";
  1119.         break;
  1120.     case ANY:
  1121.         p = "ANY";
  1122.         break;
  1123.     case ANYOF:
  1124.         p = "ANYOF";
  1125.         break;
  1126.     case ANYBUT:
  1127.         p = "ANYBUT";
  1128.         break;
  1129.     case BRANCH:
  1130.         p = "BRANCH";
  1131.         break;
  1132.     case EXACTLY:
  1133.         p = "EXACTLY";
  1134.         break;
  1135.     case NOTHING:
  1136.         p = "NOTHING";
  1137.         break;
  1138.     case BACK:
  1139.         p = "BACK";
  1140.         break;
  1141.     case END:
  1142.         p = "END";
  1143.         break;
  1144.     case OPEN+1:
  1145.     case OPEN+2:
  1146.     case OPEN+3:
  1147.     case OPEN+4:
  1148.     case OPEN+5:
  1149.     case OPEN+6:
  1150.     case OPEN+7:
  1151.     case OPEN+8:
  1152.     case OPEN+9:
  1153.         sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
  1154.         p = NULL;
  1155.         break;
  1156.     case CLOSE+1:
  1157.     case CLOSE+2:
  1158.     case CLOSE+3:
  1159.     case CLOSE+4:
  1160.     case CLOSE+5:
  1161.     case CLOSE+6:
  1162.     case CLOSE+7:
  1163.     case CLOSE+8:
  1164.     case CLOSE+9:
  1165.         sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
  1166.         p = NULL;
  1167.         break;
  1168.     case STAR:
  1169.         p = "STAR";
  1170.         break;
  1171.     case PLUS:
  1172.         p = "PLUS";
  1173.         break;
  1174.     default:
  1175.         regerror("corrupted opcode");
  1176.         break;
  1177.     }
  1178.     if (p != NULL)
  1179.         (void) strcat(buf, p);
  1180.     return(buf);
  1181. }
  1182. #endif
  1183.  
  1184. /*
  1185.  * The following is provided for those people who do not have strcspn() in
  1186.  * their C libraries.  They should get off their butts and do something
  1187.  * about it; at least one public-domain implementation of those (highly
  1188.  * useful) string routines has been published on Usenet.
  1189.  */
  1190. #ifdef STRCSPN
  1191. /*
  1192.  * strcspn - find length of initial segment of s1 consisting entirely
  1193.  * of characters not from s2
  1194.  */
  1195.  
  1196. static int
  1197. strcspn(s1, s2)
  1198. char *s1;
  1199. char *s2;
  1200. {
  1201.     register char *scan1;
  1202.     register char *scan2;
  1203.     register int count;
  1204.  
  1205.     count = 0;
  1206.     for (scan1 = s1; *scan1 != '\0'; scan1++) {
  1207.         for (scan2 = s2; *scan2 != '\0';)    /* ++ moved down. */
  1208.             if (*scan1 == *scan2++)
  1209.                 return(count);
  1210.         count++;
  1211.     }
  1212.     return(count);
  1213. }
  1214. #endif
  1215.  
  1216. void regerror(char *s)
  1217. {
  1218.     fprintf(stderr, "regerror: %s\n", s);
  1219. }
  1220.